class ConnectionManager
	def joinnet(user_id,friend_id,routerip,port,ips,sid)
	    uc=UserConnection.find(:first,:conditions=>["user_id=:user_id and friend_id=:user_id",{:user_id=>user_id}])
   		if(uc.nil?)
   			uc=UserConnection.new()
   			uc.user_id = user_id
			uc.friend_id=friend_id
		end
		refreshconnection(uc,routerip,port,ips,sid)
	end
	def build_mynet(id,routerip,port,ips,sid)
		joinnet(id,id,routerip,port,ips,sid)
	end
	def refreshconnection(uc,routerip,port,ips,sid)
		uc.routerip=routerip
		uc.port=port
		uc.thetime=Time.new
		uc.session_id=sid unless sid.nil? || sid.blank?
		uc.ips=ips unless ips.nil?|| ips.blank?
		uc.save
	end
	def refresh_mynet(id,routerip,port,ips,sid)
		build_mynet(id,routerip,port,ips,sid)
		#join friends' net
		friends=Friend.find(:all,:conditions=>['uc.id is null and friends.user_id=:user_id ',{:user_id=>id}],:joins=>"left join user_connections as uc on (friends.friend_id=uc.user_id and friends.user_id=uc.friend_id )")
		unless friends.nil?
			friends.each{|f|
	   			uc=UserConnection.new()
	   			uc.friend_id = f.user_id
				uc.user_id=f.friend_id
				uc.save
			}
		end
	end
end